package gui.storageunit;

import facades.StorageFacade;
import gui.common.*;
import gui.inventory.ProductContainerData;

import java.util.Observer;
import java.util.Observable;

import coreModel.HIT;
import coreModel.ProductContainer;
import coreModel.StorageUnit;


/**
 * Controller class for the add storage unit view.
 */
public class AddStorageUnitController extends Controller implements
IAddStorageUnitController {

	/**
	 * Constructor.
	 * 
	 * @param view Reference to add storage unit view
	 */
	public AddStorageUnitController(IView view) {
		super(view);

		construct();
		getView().enableOK(false);
		getView().enableStorageUnitName(true);
	}

	//
	// Controller overrides
	//

	/**
	 * Returns a reference to the view for this controller.
	 * 
	 * {@pre None}
	 * 
	 * {@post Returns a reference to the view for this controller.}
	 */
	@Override
	protected IAddStorageUnitView getView() {
		return (IAddStorageUnitView)super.getView();
	}

	/**
	 * Sets the enable/disable state of all components in the controller's view.
	 * A component should be enabled only if the user is currently
	 * allowed to interact with that component.
	 * 
	 * {@pre None}
	 * 
	 * {@post The enable/disable state of all components in the controller's view
	 * have been set appropriately.}
	 */
	@Override
	protected void enableComponents() 
	{
		boolean enable=true;
		try
		{
			if(getView().getStorageUnitName().length()>0 &&
					HIT.getInstance().canAddStorageUnit(
							new StorageUnit(getView().getStorageUnitName())))
			{
				enable&=true;
			}
			else
				enable=false;
		}
		catch(Exception e)
		{
			enable=false;
		}
		getView().enableOK(enable);
	}

	/**
	 * Loads data into the controller's view.
	 * 
	 *  {@pre None}
	 *  
	 *  {@post The controller has loaded data into its view}
	 */
	@Override
	protected void loadValues() 
	{
		//I don't beleive there is anything to do for this
	}

	//
	// IAddStorageUnitController overrides
	//

	/**
	 * This method is called when any of the fields in the
	 * add storage unit view is changed by the user.
	 */
	@Override
	public void valuesChanged() 
	{
		enableComponents();
	}

	/**
	 * This method is called when the user clicks the "OK"
	 * button in the add storage unit view.
	 */
	@Override
	public void addStorageUnit() 
	{
		try
		{
			// This code was modified by Ammon to set the selected StorageUnit
			// after adding it
			String suName = getView().getStorageUnitName();
			StorageUnit tmpSU = new StorageUnit( suName );
			
			ProductContainerData tmpPCD = new ProductContainerData();
			tmpPCD.setTag((ProductContainer)tmpSU);
			
			GUISelections.getInstance().setContainer( tmpPCD );
			
			StorageFacade.getInstance().addStorageUnit(	tmpSU );
		}
		catch(Exception e)
		{
			//Should never get here
			e.printStackTrace();
		}
	}



}

